<?php
// +----------------------------------------------------------------------
// | Copyright (c) 2020 All rights reserved.
// +----------------------------------------------------------------------
// | User: Simony <1362229026@qq.com>
// | wechat: Shen86579595
// +----------------------------------------------------------------------

namespace easemob;

use GuzzleHttp\Client;
use GuzzleHttp\Exception\ClientException;
use GuzzleHttp\Exception\ServerException;

class EasemobIm
{
    private $_client_id;
    private $_client_secret;
    private $_org_name;
    private $_app_name;
    private $_domain = 'http://a1.easemob.com/';
    private $_url;
    private $_http_errors = false;
//------------------------------------------------------用户体系

    /**
     * User:Simony
     * Function: 初始化
     * 初始化参数
     * EasemobIm constructor.
     * @param $options
     */
    public function __construct()
    {

        $easemobleConfig = sysConfig('easemob');
        $this->_org_name = $easemobleConfig ['org_name'] ?? '';
        $this->_app_name = $easemobleConfig ['app_name'] ?? '';
        $this->_client_id = $easemobleConfig ['client_id'] ?? '';
        $this->_client_secret = $easemobleConfig ['client_secret'] ?? '';

        if (!empty ($this->_org_name) && !empty ($this->_app_name)) {
            $this->_url = $this->_domain . $this->_org_name . '/' . $this->_app_name . '/';
        } else {
            return ds_arr(ERROR, '缺少参数');
        }
    }


    /**
     * User:Simony
     * Function: 获取token
     * @return string
     */
    public function getToken()
    {
        $token = cache('easemoblm');
        if (!empty($token)) {
            $url = $this->_url . 'token';
            $params = [
                'http_errors' => $this->_http_errors,
                'json' => [
                    'grant_type' => 'client_credentials',
                    'client_id' => $this->_client_id,
                    'client_secret' => $this->_client_secret
                ]
            ];
            $res = $this->postCurl($url, $params, 'POST');
            if (isset($res['code']) && $res['code'] == ERROR) return ds_arr($res['code'], $res['msg']);

            $res = $res['result'];
            $token = 'Bearer ' . $res['access_token'];

            cache('easemoblm', $token, intval($res['expires_in']) - 60);
        }

        return $token;
    }


    /**
     * User:Simony
     * Function:发送文本消息
     * @param string $from
     * @param $target_type
     * @param $target
     * @param $content
     * @param $ext
     * @return bool|mixed|string
     */
    public function sendText($from = "admin", $target_type = 'users', $target = [], $content, $ext = ['type' => 1])
    {
        $form_member = model('common/member/Member')->getInfoByID($from);
        if ($form_member) $ext = array_merge($ext, ['avatar' => $form_member['avatar'], 'nickname' => $form_member['nickname']]);
        $url = $this->_url . 'messages';
        $params = [
            'http_errors' => $this->_http_errors,
            'headers' => [
                'Authorization' => $this->getToken(),
            ],
            'json' => [
                'target_type' => $target_type,
                'target' => $target,
                'msg' => [
                    'type' => 'txt',
                    'msg' => $content,
                ],
                'from' => $from,
                'ext' => $ext
            ],

        ];
        $res = $this->postCurl($url, $params, 'POST');
        return ds_arr($res['code'], $res['msg'], $res['result']);
    }


    /**
     * User:Simony
     * Function:发图片消息
     * @param $filePath
     * @param string $from
     * @param $target_type
     * @param $target
     * @param $filename
     * @param $ext
     * @return bool|mixed|string
     */
    public function sendImage($file, $filename, $target, $from = "admin", $target_type = 'users', $ext = [])
    {
        $url = $this->_url . 'messages';
        $upload_result = $this->uploadFile($file);

        if ($upload_result['code'] != SUCCESS) return ds_arr($upload_result['code'], $upload_result['msg'], $upload_result['result']);

        $json_url = $upload_result['result']['uri'] . '/' . $upload_result['result']['entities'][0]['uuid'];
        $params = [
            'http_errors' => $this->_http_errors,
            'headers' => [
                'Authorization' => $this->getToken(),
            ],
            'json' => [
                'target_type' => $target_type,
                'target' => $target,
                'msg' => [
                    'type' => 'img',
                    'filename' => $filename,
                    'secret' => $upload_result['result']['entities'][0]['share-secret'],
                    'url' => $json_url,
                    'size' => [
                        'width' => 480,
                        'height' => 720
                    ],
                ],
                'from' => $from,
            ],
        ];
        if (!empty($ext)) $params['json']['ext'] = $ext;

        $res = $this->postCurl($url, $params, 'POST');


        $res['result']['url'] = $json_url;
        return ds_arr($res['code'], $res['msg'], $res['result']);
    }


    /**
     * User:Simony
     * Function:授权注册
     * @param $username
     * @param $password
     * @return bool|mixed|string
     */
    public function createUser($username, $nickname = '', $password)
    {

        $url = $this->_url . 'users';
        $params = [
            'http_errors' => $this->_http_errors,
            'headers' => [
                'Authorization' => $this->getToken(),
            ],
            'json' => [
                'username' => $username,
                'password' => $password,
                'nickname' => $nickname
            ],

        ];
        $res = $this->postCurl($url, $params, 'POST');

        return ds_arr($res['code'], $res['msg'], $res['result']);
    }


    /**
     * User:Simony
     * Function:上传图片或文件
     * @param $filePath
     * @return bool|mixed|string
     */
    public function uploadFile($file)
    {

        $url = $this->_url . 'chatfiles';
        $params = [
            'http_errors' => $this->_http_errors,
            'headers' => [
                'restrict-access' => false,
                'Authorization' => $this->getToken(),
                'Accept' => 'application/json',
            ],
            'multipart' => [
                [
                    'name' => 'file',
                    'contents' => $file
                ],

            ],
        ];

        $res = $this->postCurl($url, $params, 'POST');


        return ds_arr($res['code'], $res['msg'], $res['result']);

    }


    /**
     * User:Simony
     * Function:导出聊天记录
     * @param $ql
     * @return bool|mixed|string
     */
    public function getChatRecord($time)
    {
        $url = $this->_url . 'chatmessages/' . $time;
        $params = [
            'http_errors' => $this->_http_errors,
            'headers' => [
                'Authorization' => $this->getToken(),
            ]
        ];

        $res = $this->postCurl($url, $params, "GET");
        return ds_arr($res['code'], $res['msg'], $res['result']);
    }


    //-------------------------------------------------------------聊天室操作-------------------------------------

    /**
     * User:Simony
     * Function:创建聊天室
     * @param $options
     * @return bool|mixed|string
     */
    public function createChatRoom($name, $owner, $members, $description = '', $maxusers = 5000)
    {
        $url = $this->_url . 'chatrooms';
        $params = [
            'http_errors' => $this->_http_errors,
            'headers' => [
                'Authorization' => $this->getToken(),
            ],
            'json' => [
                'name' => $name,
                'description' => $description,
                'maxusers' => $maxusers,
                'owner' => (string)$owner,
                'members' => $members
            ],

        ];

        $res = $this->postCurl($url, $params, "post");
        return ds_arr($res['code'], $res['msg'], $res['result']);
    }

    //-------------------------------------------------------------群操作-------------------------------------

    /**
     * User:Simony
     * Function:创建一个群组
     * @param $options
     * @return bool|mixed|string
     */
    public function createGroup($groupname, $desc, $owner, $members = [], $public = true, $maxusers = 2000)
    {
        $url = $this->_url . 'chatgroups';
        $params = [
            'http_errors' => $this->_http_errors,
            'headers' => [
                'Authorization' => $this->getToken(),
            ],
            'json' => [
                'groupname' => $groupname,
                'desc' => $desc,
                'maxusers' => $maxusers,
                'owner' => (string)$owner,
                'public' => $public
            ],

        ];
        if (!empty($members)) $params['json']['members'] = $members;


        $res = $this->postCurl($url, $params, "post");
        return ds_arr($res['code'], $res['msg'], $res['result']);
    }


    /**
     * User:Simony
     * Function:群组单个加人
     * @param $group_id
     * @param $username
     * @return bool|mixed|string
     */
    public function addGroupMember($group_id, $username)
    {
        $url = $this->_url . 'chatgroups/' . $group_id . '/users/' . $username;
        $params = [
            'http_errors' => true,
            'headers' => [
                'Authorization' => $this->getToken(),
            ],
        ];
        if (!empty($members)) $params['json']['members'] = $members;


        $res = $this->postCurl($url, $params, "post");
        return ds_arr($res['code'], $res['msg'], $res['result']);
    }


    /**
     * User: Simony
     * Function: 获取数据
     * @param $url
     * @param $params
     * @param string $type
     * @return mixed|string
     */
    public function postCurl($url, $params, $type = 'POST')
    {
        $type = strtoupper($type);

        try {
            $client = new Client();
            $response = $client->request($type, $url, $params);
            $res = $response->getBody()->getContents();
            $res = json_decode($res, true);

            return isset($res['error']) ? ds_arr(ERROR, $res['error'], $res) : ds_arr(SUCCESS, '调用成功', $res);
        } catch (ServerException $e) {

            return ds_arr(ERROR, $e->getMessage());
        } catch (ClientException $e) {
            return ds_arr(ERROR, $e->getMessage());
        }
    }
}
